package com.bhs.sansonglogistics.ui.enterprise;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.ArrayMap;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Switch;
import android.widget.TextView;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.AppManager;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.base.BaseBean;
import com.bhs.sansonglogistics.bean.AddLineBean;
import com.bhs.sansonglogistics.bean.PriceBean;
import com.bhs.sansonglogistics.bean.ShipmentsBean;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.bhs.sansonglogistics.view.MoneyValueFilter;
import com.google.gson.Gson;

import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 添加专线2
 */
public class AddLine2Activity extends BaseActivity implements TextWatcher, NetCallBack {


    private Switch mSwOffer;
    private EditText mEtGeneralSlowDay;
    private EditText mEtGeneralQuickDay;
    private EditText mEtGeneral1to1;
    private EditText mEtGeneral1to3;
    private EditText mEtGeneral1to6;
    private EditText mEtGeneral1to10;
    private EditText mEtExpressSlowDay;
    private EditText mEtExpressQuickDay;
    private EditText mEtExpress1to1;
    private EditText mEtExpress1to3;
    private EditText mEtExpress1to6;
    private EditText mEtExpress1to10;
    private CheckBox mCbPickGoods;
    private EditText mEtPickGoodsMoney;
    private CheckBox mCbHomeDelivery;
    private EditText mEtHomeDeliveryMoney;
    private Button mBtnSubmit;
    private AddLineBean addLineBean;
    private TextView mTvPickGoods;
    private TextView mTvHomeDelivery;
    private int line_id;

    @Override
    public int initLayout() {
        return R.layout.activity_add_line2;
    }

    @Override
    public void initView() {
        addLineBean = (AddLineBean) getIntent().getSerializableExtra("data");
        line_id = getIntent().getIntExtra("line_id", 0);
        TextView mTvTitle = findViewById(R.id.tv_title);
        mTvTitle.setText("添加专线");
        mSwOffer = findViewById(R.id.sw_offer);
        mEtGeneralSlowDay = findViewById(R.id.et_general_slow_day);
        mEtGeneralQuickDay = findViewById(R.id.et_general_quick_day);
        mEtGeneral1to1 = findViewById(R.id.et_general_1to1);
        mEtGeneral1to3 = findViewById(R.id.et_general_1to3);
        mEtGeneral1to6 = findViewById(R.id.et_general_1to6);
        mEtGeneral1to10 = findViewById(R.id.et_general_1to10);
        mEtExpressSlowDay = findViewById(R.id.et_express_slow_day);
        mEtExpressQuickDay = findViewById(R.id.et_express_quick_day);
        mEtExpress1to1 = findViewById(R.id.et_express_1to1);
        mEtExpress1to3 = findViewById(R.id.et_express_1to3);
        mEtExpress1to6 = findViewById(R.id.et_express_1to6);
        mEtExpress1to10 = findViewById(R.id.et_express_1to10);
        mCbPickGoods = findViewById(R.id.cb_pick_goods);
        mEtPickGoodsMoney = findViewById(R.id.et_pick_goods_money);
        mCbHomeDelivery = findViewById(R.id.cb_home_delivery);
        mEtHomeDeliveryMoney = findViewById(R.id.et_home_delivery_money);
        mBtnSubmit = findViewById(R.id.btn_submit);
        mEtGeneralSlowDay.addTextChangedListener(this);
        mEtExpressSlowDay.addTextChangedListener(this);
        mEtExpressQuickDay.addTextChangedListener(this);
        mEtPickGoodsMoney.addTextChangedListener(this);
        mEtHomeDeliveryMoney.addTextChangedListener(this);
        mEtGeneral1to1.addTextChangedListener(this);
        mEtGeneral1to3.addTextChangedListener(this);
        mEtGeneral1to6.addTextChangedListener(this);
        mEtGeneral1to10.addTextChangedListener(this);
        mEtExpressSlowDay.addTextChangedListener(this);
        mEtExpressQuickDay.addTextChangedListener(this);
        mEtExpress1to1.addTextChangedListener(this);
        mEtExpress1to3.addTextChangedListener(this);
        mEtExpress1to6.addTextChangedListener(this);
        mEtExpress1to10.addTextChangedListener(this);
        mTvPickGoods = findViewById(R.id.tv_pick_goods);
        mTvHomeDelivery = findViewById(R.id.tv_home_delivery);
        if (line_id > 0) {
            networkRequest(netApi.getSpecialLineInfo(line_id), this, 9527);
        }

        mEtGeneral1to1.setFilters(new InputFilter[]{new MoneyValueFilter()});
        mEtGeneral1to3.setFilters(new InputFilter[]{new MoneyValueFilter()});
        mEtGeneral1to6.setFilters(new InputFilter[]{new MoneyValueFilter()});
        mEtGeneral1to10.setFilters(new InputFilter[]{new MoneyValueFilter()});

        mEtExpress1to1.setFilters(new InputFilter[]{new MoneyValueFilter()});
        mEtExpress1to3.setFilters(new InputFilter[]{new MoneyValueFilter()});
        mEtExpress1to6.setFilters(new InputFilter[]{new MoneyValueFilter()});
        mEtExpress1to10.setFilters(new InputFilter[]{new MoneyValueFilter()});
        mEtPickGoodsMoney.setFilters(new InputFilter[]{new MoneyValueFilter()});
        mEtHomeDeliveryMoney.setFilters(new InputFilter[]{new MoneyValueFilter()});
    }

    Drawable drawable;

    @Override
    public void initData() {
        drawable = getDrawable(R.mipmap.ic_asterisk);
        // 这一步必须要做，否则不会显示。
        drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                drawable.getMinimumHeight());
        mBtnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                submit();
            }
        });

        mCbHomeDelivery.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    mTvHomeDelivery.setCompoundDrawables(drawable, null, null, null);
                } else {
                    mTvHomeDelivery.setCompoundDrawables(null, null, null, null);
                }
                verify();
            }
        });
        mCbPickGoods.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    mTvPickGoods.setCompoundDrawables(drawable, null, null, null);
                } else {
                    mTvPickGoods.setCompoundDrawables(null, null, null, null);
                }
                verify();
            }
        });
        mEtGeneralQuickDay.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
            @Override
            public void afterTextChanged(Editable editable) {
                if(!TextUtils.isEmpty(editable.toString())&&!TextUtils.isEmpty(mEtGeneralSlowDay.getText().toString())){
                   if(Integer.parseInt(mEtGeneralQuickDay.getText().toString())<Integer.parseInt(mEtGeneralSlowDay.getText().toString())){
                       mEtGeneralQuickDay.setText("");
                       ToastUtil.show("天数必须大于左边");
                   }
                }
                verify();
            }
        });

        mEtExpressQuickDay.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
            @Override
            public void afterTextChanged(Editable editable) {
                if(!TextUtils.isEmpty(editable.toString())&&!TextUtils.isEmpty(mEtExpressSlowDay.getText().toString())){
                    if(Integer.parseInt(mEtExpressQuickDay.getText().toString())<Integer.parseInt(mEtExpressSlowDay.getText().toString())){
                        mEtExpressQuickDay.setText("");
                        ToastUtil.show("天数必须大于左边");
                    }
                }
                verify();
            }
        });
    }

    private void submit() {
        Map<String, String> map = new ArrayMap<>();
        LogUtils.d(addLineBean.outlets_ids);
        map.put("outlets_ids", addLineBean.outlets_ids);
        map.put("line_contact", addLineBean.line_contact);
        map.put("line_mobile", addLineBean.line_mobile);
        map.put("start_province", addLineBean.start_province);
        map.put("start_city", addLineBean.start_city);
        map.put("start_county", addLineBean.start_county);
        map.put("end_province", addLineBean.end_province);
        map.put("end_city", addLineBean.end_city);
        map.put("end_county", addLineBean.end_county);
        map.put("general_day_min", mEtGeneralSlowDay.getText().toString());
        map.put("general_day_max", mEtGeneralQuickDay.getText().toString());
        map.put("fast_day_min", mEtExpressSlowDay.getText().toString());
        map.put("fast_day_max", mEtExpressQuickDay.getText().toString());
        map.put("dispatch_status", mCbPickGoods.isChecked() ? "1" : "0");
        map.put("dispatch_price", mEtPickGoodsMoney.getText().toString());
        map.put("self_status", mCbHomeDelivery.isChecked() ? "1" : "0");
        map.put("self_price", mEtHomeDeliveryMoney.getText().toString());
        map.put("price_show_status", mSwOffer.isChecked() ? "1" : "0");
        Map<String, String> generalMap = new ArrayMap<>();
        generalMap.put("P1", mEtGeneral1to1.getText().toString());
        generalMap.put("P3", mEtGeneral1to3.getText().toString());
        generalMap.put("P6", mEtGeneral1to6.getText().toString());
        generalMap.put("P10", mEtGeneral1to10.getText().toString());
        Map<String, String> fastMap = new ArrayMap<>();
        fastMap.put("P1", mEtExpress1to1.getText().toString());
        fastMap.put("P3", mEtExpress1to3.getText().toString());
        fastMap.put("P6", mEtExpress1to6.getText().toString());
        fastMap.put("P10", mEtExpress1to10.getText().toString());
        map.put("general_price_json", mapToJson(generalMap));
        map.put("fast_price_json", mapToJson(fastMap));
        if (line_id > 0) {
            map.put("line_id",String.valueOf(line_id));
            networkRequest(netApi.edit_special_line(map), AddLine2Activity.this);
        } else {
            networkRequest(netApi.addLine(map), AddLine2Activity.this);
        }
    }


    private int digits = 2;
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void onTextChanged(CharSequence s, int i, int i1, int i2) {
    }

    @Override
    public void afterTextChanged(Editable editable) {
        verify();
    }

    private void verify() {
        boolean verify = true;
        if (TextUtils.isEmpty(mEtExpressQuickDay.getText()) || TextUtils.isEmpty(mEtExpressSlowDay.getText())) {
            verify = false;
        }
        if (TextUtils.isEmpty(mEtGeneralQuickDay.getText()) || TextUtils.isEmpty(mEtGeneralSlowDay.getText())) {
            verify = false;
        }
        if (mCbPickGoods.isChecked() && TextUtils.isEmpty(mEtPickGoodsMoney.getText())) {
            verify = false;
        }
        if (mCbHomeDelivery.isChecked() && TextUtils.isEmpty(mEtHomeDeliveryMoney.getText())) {
            verify = false;
        }
        if (TextUtils.isEmpty(mEtGeneral1to1.getText()) || TextUtils.isEmpty(mEtGeneral1to3.getText())
                || TextUtils.isEmpty(mEtGeneral1to6.getText()) || TextUtils.isEmpty(mEtGeneral1to10.getText())) {
            verify = false;
        }

        if (TextUtils.isEmpty(mEtExpress1to1.getText()) || TextUtils.isEmpty(mEtExpress1to3.getText())
                || TextUtils.isEmpty(mEtExpress1to6.getText()) || TextUtils.isEmpty(mEtExpress1to10.getText())) {
            verify = false;
        }
        mBtnSubmit.setEnabled(verify);
        mBtnSubmit.setBackgroundColor(verify ? Color.parseColor("#485EF4") : Color.parseColor("#7F485EF4"));
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 9527) {
            ShipmentsBean shipmentsBean = new Gson().fromJson(json, ShipmentsBean.class);
            if (shipmentsBean.isStatus()) {
                ShipmentsBean.DataDTO.InfoDTO data = shipmentsBean.getData().getInfo();
                mSwOffer.setChecked(data.getPrice_show_status() == 1);
                mEtGeneralSlowDay.setText(String.valueOf(data.getGeneral_day_min()));
                mEtGeneralQuickDay.setText(String.valueOf(data.getGeneral_day_max()));
                PriceBean priceBean2 = new Gson().fromJson(data.getGeneral_price_json(), PriceBean.class);
                mEtGeneral1to1.setText(priceBean2.P1);
                mEtGeneral1to3.setText(priceBean2.P3);
                mEtGeneral1to6.setText(priceBean2.P6);
                mEtGeneral1to10.setText(priceBean2.P10);
                mEtExpressSlowDay.setText(String.valueOf(data.getFast_day_min()));
                mEtExpressQuickDay.setText(String.valueOf(data.getFast_day_max()));
                PriceBean priceBean = new Gson().fromJson(data.getFast_price_json(), PriceBean.class);
                mEtExpress1to1.setText(priceBean.P1);
                mEtExpress1to3.setText(priceBean.P3);
                mEtExpress1to6.setText(priceBean.P6);
                mEtExpress1to10.setText(priceBean.P10);
                mCbPickGoods.setChecked(data.getDispatch_status() == 1);
                mEtPickGoodsMoney.setText(data.getDispatch_price());
                mCbHomeDelivery.setChecked(data.getSelf_status() == 1);
                mEtHomeDeliveryMoney.setText(data.getSelf_price());
            } else {
                ToastUtil.show(shipmentsBean.getMsg());
            }
        } else {
            BaseBean bean = new Gson().fromJson(json, BaseBean.class);
            ToastUtil.show(bean.getMsg());
            if (bean.isStatus()) {
                finish();
                AppManager.getInstance().finishActivity(AddLineActivity.class);
                startActivity(new Intent(mActivity, DedicatedLineManagementActivity.class));
            }
        }
    }

    @Override
    public void onFailure(int requestCode) {

    }

    /**
     * 将Map转化为Json
     */
    public String mapToJson(Map<String, String> map) {
        Gson gson = new Gson();
        String jsonStr = gson.toJson(map);
        return jsonStr;
    }

}